package cool.webstudy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cool.webstudy.admin.constant.enums.DelFlagEnum;
import cool.webstudy.admin.constant.enums.EnabledStatusFlagEnum;
import cool.webstudy.admin.constant.enums.rescode.TeamUserResCodeEnum;
import cool.webstudy.admin.constant.enums.rescode.UserResCodeEnum;
import cool.webstudy.admin.exception.BusinessException;
import cool.webstudy.admin.mapper.team.user.TeamUserMapper;
import cool.webstudy.admin.model.dto.team.TeamDetailInfoDTO;
import cool.webstudy.admin.model.dto.team.user.CreateTeamUserDTO;
import cool.webstudy.admin.model.dto.team.user.PaginationQueryTeamUserInfoListDTO;
import cool.webstudy.admin.model.dto.team.user.TeamUserDetailInfoDTO;
import cool.webstudy.admin.model.dto.team.user.UpdateTeamUserDTO;
import cool.webstudy.admin.model.dto.user.UserDetailInfoDTO;
import cool.webstudy.admin.model.po.team.user.TeamUserPO;
import cool.webstudy.admin.model.vo.team.QueryOwnTeamDetailInfoVO;
import cool.webstudy.admin.model.vo.team.QueryTeamRoughInfoVO;
import cool.webstudy.admin.model.vo.team.user.PaginationQueryTeamUserInfoListVO;
import cool.webstudy.admin.model.vo.team.user.QueryTeamUserDetailInfoVO;
import cool.webstudy.admin.service.TeamService;
import cool.webstudy.admin.service.TeamUserService;
import cool.webstudy.admin.utils.UserDetailUtil;
import cool.webstudy.common.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 队伍与用户关系管理接口实现类
 */
@Service
public class TeamUserServiceImpl implements TeamUserService {
    @Autowired
    private TeamUserMapper teamUserMapper;
    @Autowired
    private TeamService teamService;
    /**
     *
     * @param unCode 队伍业务主键
     * @return TeamUserPO 队伍与用户关系信息实体
     * @description: 判断队伍与用户关系是否存在，如果存在，则返回该队伍与用户关系的信息实体
     */
    @Override
    public TeamUserPO isExist(String unCode) {
        LambdaQueryWrapper<TeamUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamUserPO::getUnCode, unCode)
                .eq(TeamUserPO::getUserName, EnabledStatusFlagEnum.ENABLED.getFlag());
        TeamUserPO teamUserPO = teamUserMapper.selectOne(queryWrapper);
        if (Objects.nonNull(teamUserPO)){
            return teamUserPO;
        }
        return null;
    }

    /**
     * @param unCode 业务主键
     * @return QueryTeamUserDetailInfoVO 查询队伍与用户关系详细信息接口响应参数模型
     * @description: 查询队伍与用户关系详细信息
     */
    @Override
    public QueryTeamUserDetailInfoVO queryTeamUserDetailInfo(String unCode) {
        LambdaQueryWrapper<TeamUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamUserPO::getUnCode, unCode)
                .select(TeamUserPO::getUnCode, TeamUserPO::getTeamUnCode, TeamUserPO::getUserUnCode, TeamUserPO::getUserName, TeamUserPO::getUserRoleUnCode, TeamUserPO::getUserRoleName);
        TeamUserPO teamUserPO = teamUserMapper.selectOne(queryWrapper);
        if (Objects.isNull(teamUserPO)) {
            throw new BusinessException(TeamUserResCodeEnum.RC_TEAM_USER_NOT_EXIST);
        }
        QueryTeamUserDetailInfoVO queryTeamUserDetailInfoVO = new QueryTeamUserDetailInfoVO();
        queryTeamUserDetailInfoVO.setUnCode(teamUserPO.getUnCode());
        queryTeamUserDetailInfoVO.setTeamUnCode(teamUserPO.getTeamUnCode());
        queryTeamUserDetailInfoVO.setUserUnCode(teamUserPO.getUserUnCode());
        queryTeamUserDetailInfoVO.setUserName(teamUserPO.getUserName());
        queryTeamUserDetailInfoVO.setUserRoleUnCode(teamUserPO.getUserRoleUnCode());
        queryTeamUserDetailInfoVO.setUserRoleName(teamUserPO.getUserRoleName());
        return queryTeamUserDetailInfoVO;
    }

    @Override
    public QueryTeamUserDetailInfoVO queryTeamUserDetailInfoByUserUnCode(String userUnCode) {
        LambdaQueryWrapper<TeamUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamUserPO::getUserUnCode, userUnCode)
                .select(TeamUserPO::getUnCode, TeamUserPO::getTeamUnCode, TeamUserPO::getUserUnCode, TeamUserPO::getUserName, TeamUserPO::getUserRoleUnCode, TeamUserPO::getUserRoleName);
        TeamUserPO teamUserPO = teamUserMapper.selectOne(queryWrapper);
        if(Objects.isNull(teamUserPO)){
            throw new BusinessException(TeamUserResCodeEnum.RC_TEAM_USER_NOT_EXIST);
        }
        QueryTeamUserDetailInfoVO queryTeamUserDetailInfoVO = new QueryTeamUserDetailInfoVO();
        queryTeamUserDetailInfoVO.setUnCode(teamUserPO.getUnCode());
        queryTeamUserDetailInfoVO.setTeamUnCode(teamUserPO.getTeamUnCode());
        queryTeamUserDetailInfoVO.setUserUnCode(teamUserPO.getUserUnCode());
        queryTeamUserDetailInfoVO.setUserName(teamUserPO.getUserName());
        queryTeamUserDetailInfoVO.setUserRoleUnCode(teamUserPO.getUserRoleUnCode());
        queryTeamUserDetailInfoVO.setUserRoleName(teamUserPO.getUserRoleName());
        return queryTeamUserDetailInfoVO;
    }

    /**
         * @param dto 创建队伍与用户关系接口请求参数模型
         * @return Boolean 是否成功标识
         * @description: 创建队伍与用户关系
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public Boolean createTeamUser(CreateTeamUserDTO dto) {
            UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
            TeamUserPO teamUserPO = new TeamUserPO();
            teamUserPO.setTeamUnCode(dto.getTeamUnCode());
            teamUserPO.setUserUnCode(dto.getUserUnCode());
            teamUserPO.setUserName(dto.getUserName());
            teamUserPO.setUserRoleUnCode(dto.getUserRoleUnCode());
            teamUserPO.setUserRoleName(dto.getUserRoleName());
            teamUserPO.setUnCode(UUIDUtil.getUUID());
            teamUserPO.setCreateBy(userDetailInfo.getAccount());
            teamUserPO.setCreateTime(new Date());
            teamUserPO.setUpdateBy(userDetailInfo.getAccount());
            teamUserPO.setUpdateTime(new Date());
            teamUserPO.setDelFlag(DelFlagEnum.NOT_DEL_FLAG.getFlag());
            try {
                teamUserMapper.insert(teamUserPO);
            }catch (Exception e) {
                throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_CREATE);
            }
            return true;
        }

    /**
     * @param dto 更新队伍与用户关系接口请求参数模型
     * @return Boolean 是否成功标识
     * @description: 更新队伍与用户关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTeamUser(UpdateTeamUserDTO dto) {
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        LambdaUpdateWrapper<TeamUserPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeamUserPO::getUnCode, dto.getUnCode())
                .set(StringUtils.isNotBlank(dto.getTeamUnCode()), TeamUserPO::getTeamUnCode, dto.getTeamUnCode())
                .set(StringUtils.isNotBlank(dto.getUserUnCode()), TeamUserPO::getUserUnCode, dto.getUserUnCode())
                .set(StringUtils.isNotBlank(dto.getUserName()), TeamUserPO::getUserName, dto.getUserName())
                .set(StringUtils.isNotBlank(dto.getUserRoleUnCode()), TeamUserPO::getUserRoleUnCode, dto.getUserRoleUnCode())
                .set(StringUtils.isNotBlank(dto.getUserRoleName()), TeamUserPO::getUserRoleName, dto.getUserRoleName())
                .set(TeamUserPO::getUpdateBy, userDetailInfo.getAccount())
                .set(TeamUserPO::getUpdateTime, new Date());
        try {
            teamUserMapper.update(null,updateWrapper);
        }catch (Exception e) {
            throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_UPDATE);
        }
        return true;
     }

    /**
     * @param unCodeList 业务主键列表
     * @return Boolean 是否成功标识
     * @description: 批量删除队伍与用户关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteTeamUser(List<String> unCodeList) {
        if (unCodeList == null || unCodeList.isEmpty()) {
            throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_DELETE);
        }
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        LambdaUpdateWrapper<TeamUserPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TeamUserPO::getUnCode, unCodeList)
                .set(TeamUserPO::getUpdateBy, userDetailInfo.getAccount())
                .set(TeamUserPO::getUpdateTime, new Date())
                .set(TeamUserPO::getDelFlag,DelFlagEnum.DEL_FLAG.getFlag());
        try {
            teamUserMapper.update(null,updateWrapper);
        }catch (Exception e) {
            throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_DELETE);
        }
        return true;
    }
    /**
     * @param dto 分页获取队伍与用户关系信息列表接口请求参数基础模型
     * @return Page<PaginationQueryTeamUserInfoListVO> 分页获取队伍与用户关系信息列表接口响应模型
     * @description: 分页获取队伍与用户关系信息列表
     */
    @Override
    public Page<PaginationQueryTeamUserInfoListVO> paginationQueryTeamUserInfoList(PaginationQueryTeamUserInfoListDTO dto) {
        Page<PaginationQueryTeamUserInfoListVO> paginationQueryTeamUserInfoListVOPage = new Page<>();
        Page<TeamUserPO> page = new Page<>(dto.getCurrent(),dto.getPageSize());
        LambdaQueryWrapper<TeamUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dto.getContext()), TeamUserPO::getUserName, dto.getContext())
                .or().like(StringUtils.isNotBlank(dto.getContext()), TeamUserPO::getUserRoleName, dto.getContext())
                .eq(TeamUserPO::getTeamUnCode, dto.getTeamUnCode());

        Page<TeamUserPO> teamUserPOPage = teamUserMapper.selectPage(page,queryWrapper);
        if(Objects.isNull(teamUserPOPage)){
            return paginationQueryTeamUserInfoListVOPage;
        }
        List<PaginationQueryTeamUserInfoListVO> paginationQueryTeamUserInfoListVOList = new ArrayList<>();
        teamUserPOPage.getRecords().forEach(teamUserPO -> {
            PaginationQueryTeamUserInfoListVO paginationQueryTeamUserInfoListVO = new PaginationQueryTeamUserInfoListVO();
            paginationQueryTeamUserInfoListVO.setUnCode(teamUserPO.getUnCode());
            paginationQueryTeamUserInfoListVO.setTeamUnCode(teamUserPO.getTeamUnCode());
            paginationQueryTeamUserInfoListVO.setUserUnCode(teamUserPO.getUserUnCode());
            paginationQueryTeamUserInfoListVO.setUserName(teamUserPO.getUserName());
            paginationQueryTeamUserInfoListVO.setUserRoleUnCode(teamUserPO.getUserRoleUnCode());
            paginationQueryTeamUserInfoListVO.setUserRoleName(teamUserPO.getUserRoleName());
            paginationQueryTeamUserInfoListVO.setCreateBy(teamUserPO.getCreateBy());
            paginationQueryTeamUserInfoListVO.setCreateTime(teamUserPO.getCreateTime());
            paginationQueryTeamUserInfoListVO.setUpdateBy(teamUserPO.getUpdateBy());
            paginationQueryTeamUserInfoListVO.setUpdateTime(teamUserPO.getUpdateTime());
            paginationQueryTeamUserInfoListVOList.add(paginationQueryTeamUserInfoListVO);
        });
        paginationQueryTeamUserInfoListVOPage.setRecords(paginationQueryTeamUserInfoListVOList);
        paginationQueryTeamUserInfoListVOPage.setCurrent(teamUserPOPage.getCurrent());
        paginationQueryTeamUserInfoListVOPage.setPages(teamUserPOPage.getPages());
        paginationQueryTeamUserInfoListVOPage.setSize(teamUserPOPage.getSize());
        paginationQueryTeamUserInfoListVOPage.setTotal(teamUserPOPage.getTotal());
        return paginationQueryTeamUserInfoListVOPage;
    }

    @Override
    public QueryOwnTeamDetailInfoVO queryOwnTeamDetailInfoVO() {
        //获取当前登录的用户信息
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        if (Objects.isNull(userDetailInfo)){
            return null;
        }
        if("system".equals(userDetailInfo.getAccount())){
            throw new BusinessException(UserResCodeEnum.RC_ERROR_NOT_LOGIN);
        }
        //查询当前登录用户的队伍信息
        LambdaQueryWrapper<TeamUserPO> teamUserWrapper = new LambdaQueryWrapper<>();
        teamUserWrapper.eq(TeamUserPO::getUserUnCode,userDetailInfo.getUnCode());
        try {
            TeamUserPO teamUserPO = teamUserMapper.selectOne(teamUserWrapper);
            if (Objects.isNull(teamUserPO)){
                throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_NOT_IN_TEAM);
            }
            QueryOwnTeamDetailInfoVO queryOwnTeamDetailInfoVO = new QueryOwnTeamDetailInfoVO();
            queryOwnTeamDetailInfoVO.setTeamUnCode(teamUserPO.getTeamUnCode());
            //查询队伍信息
            TeamDetailInfoDTO teamDetailInfoDTO = teamService.queryTeamDetailInfoDTO(teamUserPO.getTeamUnCode());
            queryOwnTeamDetailInfoVO.setTeamName(teamDetailInfoDTO.getName());
            //查询队员信息
            List<TeamUserDetailInfoDTO> teamUserDetailInfoDTOList = queryTeamUserDetailInfoDTOList(teamUserPO.getTeamUnCode());
            if (!teamUserDetailInfoDTOList.isEmpty()){
                List<QueryTeamUserDetailInfoVO> teamUserDetailInfoVOList = teamUserDetailInfoDTOList.stream()
                        .map(teamUserDetailInfoDTO -> {
                            QueryTeamUserDetailInfoVO queryTeamUserDetailInfoVO = new QueryTeamUserDetailInfoVO();
                            queryTeamUserDetailInfoVO.setUnCode(teamUserDetailInfoDTO.getUnCode());
                            queryTeamUserDetailInfoVO.setTeamUnCode(teamUserDetailInfoDTO.getTeamUnCode());
                            queryTeamUserDetailInfoVO.setUserUnCode(teamUserDetailInfoDTO.getUserUnCode());
                            queryTeamUserDetailInfoVO.setUserName(teamUserDetailInfoDTO.getUserName());
                            queryTeamUserDetailInfoVO.setUserRoleUnCode(teamUserDetailInfoDTO.getUserRoleUnCode());
                            queryTeamUserDetailInfoVO.setUserRoleName(teamUserDetailInfoDTO.getUserRoleName());
                            return queryTeamUserDetailInfoVO;
                        })
                        .collect(Collectors.toList());
                // 设置结果
                queryOwnTeamDetailInfoVO.setTeamUserList(teamUserDetailInfoVOList);
            }
            return queryOwnTeamDetailInfoVO;
        } catch (Exception e) {
            throw new BusinessException(TeamUserResCodeEnum.RC_TEAM_USER_NOT_EXIST);
        }
    }

    @Override
    public List<TeamUserDetailInfoDTO> queryTeamUserDetailInfoDTOList(String teamUnCode) {
        if (StringUtils.isBlank(teamUnCode)){
            return List.of();
        }
        LambdaQueryWrapper<TeamUserPO> teamUserWrapper = new LambdaQueryWrapper<>();
        teamUserWrapper.eq(TeamUserPO::getTeamUnCode,teamUnCode);
        try {
            List<TeamUserPO> teamUserPOList = teamUserMapper.selectList(teamUserWrapper);
            List<TeamUserDetailInfoDTO> teamUserDetailInfoDTOList = new ArrayList<>();
            if (!teamUserPOList.isEmpty()){

                teamUserPOList.forEach(teamUserPO -> {
                    TeamUserDetailInfoDTO teamUserDetailInfoDTO = new TeamUserDetailInfoDTO();
                    teamUserDetailInfoDTO.setUnCode(teamUserPO.getUnCode());
                    teamUserDetailInfoDTO.setTeamUnCode(teamUserPO.getTeamUnCode());
                    teamUserDetailInfoDTO.setUserUnCode(teamUserPO.getUserUnCode());
                    teamUserDetailInfoDTO.setUserName(teamUserPO.getUserName());
                    teamUserDetailInfoDTO.setUserRoleUnCode(teamUserPO.getUserRoleUnCode());
                    teamUserDetailInfoDTO.setUserRoleName(teamUserPO.getUserRoleName());
                    teamUserDetailInfoDTOList.add(teamUserDetailInfoDTO);
                });
            }
            return teamUserDetailInfoDTOList;
        } catch (Exception e) {
            throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_QUERY);
        }
    }

    @Override
    public TeamUserDetailInfoDTO queryTeamUserDetailInfoDTOByUserUnCode(String userUnCode) {
        if (StringUtils.isBlank(userUnCode)){
            return null;
        }
        LambdaQueryWrapper<TeamUserPO> teamUserWrapper = new LambdaQueryWrapper<>();
        teamUserWrapper.eq(TeamUserPO::getUserUnCode,userUnCode);
        try {
            TeamUserPO teamUserPO = teamUserMapper.selectOne(teamUserWrapper);
            if (Objects.isNull(teamUserPO)){
                return null;
            }
            TeamUserDetailInfoDTO teamUserDetailInfoDTO = new TeamUserDetailInfoDTO();
            teamUserDetailInfoDTO.setUnCode(teamUserPO.getUnCode());
            teamUserDetailInfoDTO.setTeamUnCode(teamUserPO.getTeamUnCode());
            teamUserDetailInfoDTO.setUserUnCode(teamUserPO.getUserUnCode());
            teamUserDetailInfoDTO.setUserName(teamUserPO.getUserName());
            teamUserDetailInfoDTO.setUserRoleUnCode(teamUserPO.getUserRoleUnCode());
            teamUserDetailInfoDTO.setUserRoleName(teamUserPO.getUserRoleName());
            return teamUserDetailInfoDTO;
        } catch (Exception e) {
            throw new BusinessException(TeamUserResCodeEnum.RC_ERROR_QUERY);
        }
    }
}

